﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace NLite.Domain.Wcf
{
    /// <summary>
    /// Encapsulates domain service response information.
    /// </summary>
    [DataContract]
    class ServiceResponse : IServiceResponse
    {
        /// <summary>
        /// Success / failure 
        /// </summary>
        [DataMember(IsRequired = true, Order = 1)]
        public bool Success { get; set; }

        /// <summary>
        /// Get or set Execption
        /// </summary>
        [DataMember(IsRequired = false, Order = 2)]
        public Exception[] Exceptions { get { return exceptions.ToArray(); } }

        [DataMember(IsRequired = false, Order = 3)]
        public Exception Exception
        {
            get { return exceptions.FirstOrDefault(); }
        }

        /// <summary>
        /// Get error collection
        /// </summary>
        [DataMember(IsRequired = false, Order = 4)]
        public ErrorState ErrorState { get; private set; }

        /// <summary>
        /// Get or set response result
        /// </summary>
        [DataMember(IsRequired = false, Order = 5)]
        public virtual object Result { get; set; }


        private List<Exception> exceptions;
        /// <summary>
        /// 
        /// </summary>
        public ServiceResponse()
        {
            ErrorState = new ErrorState();
            exceptions = new List<Exception>();
        }

        public void AddException(Exception ex)
        {
            if (ex == null)
                return;

            Success = false;
            exceptions.Add(ex);

            var nliteEx = ex as NLiteException;
            if (nliteEx != null)
            {
                if (!nliteEx.ExceptionHandled)
                    nliteEx.Handle();
            }
            else
                ex.Handle();
        }
    }
}
